package home.actions.base;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * Created by Administrator on 2015/12/10.
 */
public class DispatcherServlet extends HttpServlet {

    private HashMap<String, String> actionConf = new HashMap<>();
    private HashMap<String, String> jspConf = new HashMap<>();

    @Override
    public void init() throws ServletException {
        super.init();
        actionConf.put("index", "home.actions.main.IndexAction");
        actionConf.put("new", "home.actions.main.NewAction");
        actionConf.put("newSave", "home.actions.main.NewSaveAction");
        actionConf.put("del", "home.actions.main.DelAction");
        jspConf.put("toListPage", "list.jsp");
        jspConf.put("toNewPage", "new.jsp");
        jspConf.put("toNewSuccessPage", "newSuccess.jsp");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String actionName = req.getRequestURI().replaceAll(".*/(.*?)\\.do", "$1");
        String className = actionConf.get(actionName);
        if (className != null && !"".equals(className)) {
            try {
                Class c = Class.forName(className);
                Object o = c.newInstance();
                Method m = c.getMethod("execute", HttpServletRequest.class, HttpServletResponse.class);
                if (m != null) {
                    Object result = m.invoke(o, req, resp);
                    if (result != null) {
                        String jspName = "";
                        if (result.toString().startsWith("redirect:")) {
                            jspName = result.toString().replaceAll("redirect:", "");
                            resp.sendRedirect(jspName);
                        } else {
                            jspName = jspConf.get(result);
                            req.getRequestDispatcher(jspName).forward(req, resp);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
